import Moment from 'moment';
export default class ImageCompress{
    ctx:any;
    canvas:any;
    tctx:any;
    tcanvas:any;

    constructor() {
        this.canvas = document.createElement('canvas')
        this.ctx = this.canvas.getContext('2d')
        this.tcanvas = document.createElement('canvas')
        this.tctx = this.canvas.getContext('2d')
    }

    compress(img:HTMLImageElement) : string {
        console.log('开始压缩--------------')
        const initSize = img.src.length;
        let width = img.width;
        let height = img.height;
        let ratio;
		let location = ""
        // 大于400w像素时计算压缩比
        if ((ratio = width * height / 4000000)>1) {
            ratio = Math.sqrt(ratio);
            width /= ratio;
            height /= ratio;
        }else {
            ratio = 1;
        }

        this.canvas.width = width;
        this.canvas.height = height;

        // 铺底色
        this.ctx.fillStyle = "#fff";
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        //如果图片像素大于100万则使用瓦片绘制
        this.ctx.drawImage(img, 0, 0, width, height);
		this.ctx.save();
		this.ctx.fillStyle = "#ff2626";
		this.ctx.font = "54px bold 黑体";
		this.ctx.textAlign = "center";
		this.ctx.textBaseline = "middle";
		// var tw = this.ctx.measureText(location).width*1.2
		// if((window as any).android)
		// location = (window as any).android.getPosition_js();
		// this.ctx.fillText(location,this.canvas.width-tw,this.canvas.height-50)
		// document.body.append(this.canvas)

        //进行最小压缩
        var ndata = this.canvas.toDataURL('image/jpeg', 0.3);

        console.log('压缩前：' + initSize);
        console.log('压缩后：' + ndata.length);
        console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");

        this.tcanvas.width = this.tcanvas.height = this.canvas.width = this.canvas.height = 0;
        return ndata
    }
    compressByFile(file:any) :Promise<any> {
        return new Promise((resolve,reject) => {
			const that = this;
			const filename = '.jpg';
			// 单位kb,小于200kb则直接上传否则去压缩
			const img = new Image();
			img.src = file;
			img.onload = function() {
				const data = that.compress(img);
				const blob = that.base64ToBlob(data,'image/jpeg');
				resolve(URL.createObjectURL(blob));
			}
        }) 
    }
    calculateFileLength(str:string) {
        str=str.substring(22);
        var equalIndex= str.indexOf('=');
        if(str.indexOf('=')>0){
            str=str.substring(0, equalIndex);
        }
        var strLength=str.length;
        var fileLength=parseInt((strLength-(strLength/8)*2).toFixed(0))/1024;
        return fileLength
    }

    base64ToBlob(basestr: string,type:string) : Blob {
        var text = window.atob(basestr.split(",")[1]);
        var buffer = new ArrayBuffer(text.length);
        var ubuffer = new Uint8Array(buffer);
        var pecent = 0 , loop = null;

        for (var i = 0; i < text.length; i++) {
            ubuffer[i] = text.charCodeAt(i);
        }
        var _window = this._window();
        var Builder = _window.WebKitBlobBuilder || _window.MozBlobBuilder;
        var blob;

        if (Builder) {
            var builder = new Builder();
            builder.append(buffer);
            blob = builder.getBlob(type);
        } else {
            blob = new window.Blob([buffer], {type: type});
        }
        return blob;
    }

    _window() :any {
        return window;
    }

}